using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SharePoint.ImportExport.Core;
using SharePointExporter.FileSystem;

namespace FilesystemExtractor
{
    public partial class frmApp : Form
    {
        private string version = "0.9";

        FileParams p = null;
        public frmApp()
        {
            p=new FileParams();
            InitializeComponent();
        }

        private void lineFormatter(ErrorLevel level)
        {
            System.Drawing.Font currentFont = rtb_EventLog.SelectionFont;
            System.Drawing.FontStyle newFontStyle;

            switch (level)
            {
                case ErrorLevel.Error: // critical
                    newFontStyle = FontStyle.Bold;
                    rtb_EventLog.SelectionColor = Color.Red;
                    break;
                case ErrorLevel.Warning:  // warning
                    newFontStyle = FontStyle.Regular;
                    rtb_EventLog.SelectionColor = Color.Red;
                    break;
                default:
                    rtb_EventLog.SelectionColor = Color.Black;
                    newFontStyle = FontStyle.Regular;
                    break;
                // regular output
            }

            rtb_EventLog.SelectionFont = new Font(
            currentFont.FontFamily,
            currentFont.Size,
            newFontStyle);

        }

        /// <summary>
        /// RichTextBox Event Logger component
        /// </summary>
        public void addTextToLogRtf(string IncomingLogData)
        {
            try
            {
                string sLevel = IncomingLogData.Substring(0, IncomingLogData.IndexOf("-"));
                ErrorLevel level = (ErrorLevel)Enum.Parse(typeof(ErrorLevel), sLevel);
                lineFormatter(level);
                IncomingLogData = DateTime.Now.ToLongTimeString() + ":  " + IncomingLogData.Substring(IncomingLogData.IndexOf("-")+1) + "\n";


                //NOTE: replace rtf_eventlog with your RTF window, or text window, in your window app, to display log info.
                rtb_EventLog.AppendText(IncomingLogData);
                rtb_EventLog.Focus();
                int textLength = rtb_EventLog.TextLength;
                rtb_EventLog.SelectionStart = textLength - 1;
                rtb_EventLog.SelectionLength = 0;
                rtb_EventLog.ScrollToCaret();
                //this.Refresh();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("error while trying to write events incoming to AddTextToLogRtf function, error:" + ex.Message + ", in location:" + ex.TargetSite);
            }
            finally
            {
            }
        }
        private void IncomingEventLogData(object sender, SPEventArgs e)
        {
            try
            {
                addTextToLogRtf(e.Message);
            }
            catch (Exception ex)
            {
                string errorString = "Error in trying to find AD presence, error:" + ex.Message + ", in module:" + ex.TargetSite;
                addTextToLogRtf(errorString);
                System.Diagnostics.Debug.WriteLine(errorString);
            }
            finally
            {
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            rtb_EventLog.Clear();
            Logger.Init(txtLogFileLocation.Text + "\\Export" + DateTime.Now.ToString("MMddHHmm") + ".log", p.ReportLevel);
            Logger.LogDataSendingEvent += new Logger.LogDataEventHandler(IncomingEventLogData);
                    
            p.Contact = txtContact.Text;
            p.ContainerType = SiteType.Site;

            string[] fileextensions;
            if (txtExclusions.Text.Length > 0)
            {
                p.Exclusions = new System.Collections.ArrayList();
                fileextensions = txtExclusions.Text.Split(';');
                foreach (string extension in fileextensions)
                {
                    p.Exclusions.Add(extension);
                }
            }

            if (txtInclusions.Text == "*.*")
            {
                txtInclusions.Text = "";
            }
            if (txtInclusions.Text.Length > 0)
            {
                p.Inclusions = new System.Collections.ArrayList();
                fileextensions = txtInclusions.Text.Split(';');
                foreach (string extension in fileextensions)
                    p.Inclusions.Add(extension);
            }
            p.Owner = txtOwner.Text;
            p.ManagedPath = txtManagedPath.Text;
            p.SiteName = txtSiteName.Text;
            p.StartDirectory = txtSource.Text;
            p.OutputDirectory = txtSource.Text;
            if (radioButton1.Checked)
                p.Mode = "single";
            if (radioButton2.Checked)
                p.Mode = "multi";
            if (radioButton3.Checked)
                p.Mode = "subsite";

            p.LogDirectory = txtLogFileLocation.Text;
            p.DocumentLibraryName = txtDocumentLibraryName.Text;
            p.Compressed = chkCompressed.Checked;

            p.SiteDefinition = cmbSiteDefinition.Text;
            if(string.IsNullOrEmpty(p.SiteDefinition))
            {
                p.SiteDefinition="STS#0";
            }
            else
            {
                p.SiteDefinition=cmbSiteDefinition.Text.Substring(cmbSiteDefinition.Text.LastIndexOf(" - ")+2).Trim();
            }
            
            if (p.Compressed)
            {
                p.CompressedDirectory= txtOutputDirectory.Text;
            }

            Logger.Log(ErrorLevel.Progress, "FSOut Version " + version + " starting...");
            Logger.Log(ErrorLevel.File, "Started at "+DateTime.Now.ToString());
            FileExporter exporter = new FileExporter();
            if (!exporter.Process(p))
            {
                Logger.Log(ErrorLevel.Error, "Error when extracting the data");
            }
            else
            {
                if (!exporter.CreateContentTypes(p))
                {
                    Logger.Log(ErrorLevel.Error, "List template creation failed");
                }
                else
                {
                    if (chkCompressed.Checked && !String.IsNullOrEmpty(p.CompressedDirectory))
                    {
                        exporter.Compress(p);
                    }
                }
            }

            Logger.Log(ErrorLevel.File, "Ended at " + DateTime.Now.ToString());
            Logger.LogDataSendingEvent -= new Logger.LogDataEventHandler(IncomingEventLogData);

            try
            {
                Logger.Close();
            }
            catch (Exception Ex)
            {
            }
        }

        private void btnNext1_Click(object sender, EventArgs e)
        {
            Settings.SelectedIndex = 1;
        }

        private void btnNext2_Click(object sender, EventArgs e)
        {
            Settings.SelectedIndex = 2;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you'd like to exit?", "Close Application", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                try
                {
                    AppSettings.Default.Save();
                }
                catch
                {
                }

                this.Close();
            }
        }

        private void frmApp_Load(object sender, EventArgs e)
        {
            AppSettings.Default.Reload();

            lblOutputDirectory.Visible = chkCompressed.Checked;
            txtOutputDirectory.Visible = chkCompressed.Checked;
 
        }

        private void btnChooseSourceFolder_Click_1(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtSource.Text = folderBrowserDialog1.SelectedPath;
            }

        }

        private void btnChooseLogFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtLogFileLocation.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void chkCompressed_CheckedChanged(object sender, EventArgs e)
        {
            lblOutputDirectory.Visible = chkCompressed.Checked;
            txtOutputDirectory.Visible = chkCompressed.Checked;
        }
    }
}